package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 这个拦截器不做别的事情，只把用户传过来的请求头的用户id存入ThreadLocal
        // 1.获取请求头中的 user-info
        String userId = request.getHeader("user-info");
        if(StrUtil.isNotEmpty(userId)){
            // 3.存入上下文
            UserContext.setUser(Long.valueOf(userId));
        }
        // 4.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户
        UserContext.removeUser();
    }
}
